package cn.zl.GB28181.transmit;

import cn.zl.GB28181.transmit.event.request.ISIPRequestProcessor;
import cn.zl.GB28181.transmit.event.response.ISIPResponseProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.TimeoutEvent;
import javax.sip.TransactionTerminatedEvent;
import javax.sip.header.CSeqHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SIP信令处理类观察者
 */
@Component
public class SIPProcessorObserver implements ISIPProcessorObserver {

    private final static Logger logger = LoggerFactory.getLogger(SIPProcessorObserver.class);

    private final static Map<String, ISIPRequestProcessor> requestProcessorMap = new ConcurrentHashMap<>();
    private final static Map<String, ISIPResponseProcessor> responseProcessorMap = new ConcurrentHashMap<>();

    /**
     * 添加 request订阅
     *
     * @param method    方法名
     * @param processor 处理程序
     */
    public void addRequestProcessor(String method, ISIPRequestProcessor processor) {
        requestProcessorMap.put(method, processor);
    }

    /**
     * 添加 response订阅
     *
     * @param method    方法名
     * @param processor 处理程序
     */
    public void addResponseProcessor(String method, ISIPResponseProcessor processor) {
        responseProcessorMap.put(method, processor);
    }

    /**
     * 分发RequestEvent事件
     *
     * @param event RequestEvent事件
     */
    @Override
    @Async("TaskExecutor")
    public void processRequest(RequestEvent event) {
        Request request = event.getRequest();
        String method = request.getMethod();
        logger.info("分发RequestEvent事件 {}", request);
        ISIPRequestProcessor sipRequestProcessor = requestProcessorMap.get(method);
        if (sipRequestProcessor == null) {
            logger.warn("不支持方法{}的request", method);
            // TODO 回复错误玛
            return;
        }
        requestProcessorMap.get(method).process(event);
    }

    @Override
    @Async("TaskExecutor")
    public void processResponse(ResponseEvent event) {
        Response response = event.getResponse();
        int status = response.getStatusCode();
        // Success
        if (((status >= Response.OK) && (status < Response.MULTIPLE_CHOICES)) || status == Response.UNAUTHORIZED) {
            CSeqHeader cseqHeader = (CSeqHeader) event.getResponse().getHeader(CSeqHeader.NAME);
            String method = cseqHeader.getMethod();
            logger.info("分发ResponseEvent事件 {} {}", method, response);
            ISIPResponseProcessor sipRequestProcessor = responseProcessorMap.get(method);
            if (sipRequestProcessor != null) {
                sipRequestProcessor.process(event);
            }
//            if (status != Response.UNAUTHORIZED && event.getResponse() != null && sipSubscribe.getOkSubscribesSize() > 0 ) {
//                CallIdHeader callIdHeader = (CallIdHeader)event.getResponse().getHeader(CallIdHeader.NAME);
//                if (callIdHeader != null) {
//                    SipSubscribe.Event subscribe = sipSubscribe.getOkSubscribe(callIdHeader.getCallId());
//                    if (subscribe != null) {
//                        SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(event);
//                        sipSubscribe.removeOkSubscribe(callIdHeader.getCallId());
//                        subscribe.response(eventResult);
//                    }
//                }
//            }
        } else if ((status >= Response.TRYING) && (status < Response.OK)) {
            // 增加其它无需回复的响应，如101、180等
        } else {
            logger.warn("接收到失败的response响应！status：" + status + ",message:" + response.getReasonPhrase());
//            if (responseEvent.getResponse() != null && sipSubscribe.getErrorSubscribesSize() > 0) {
//                CallIdHeader callIdHeader = (CallIdHeader) responseEvent.getResponse().getHeader(CallIdHeader.NAME);
//                if (callIdHeader != null) {
//                    SipSubscribe.Event subscribe = sipSubscribe.getErrorSubscribe(callIdHeader.getCallId());
//                    if (subscribe != null) {
//                        SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(responseEvent);
//                        subscribe.response(eventResult);
//                        sipSubscribe.removeErrorSubscribe(callIdHeader.getCallId());
//                    }
//                }
//            }
//            if (responseEvent.getDialog() != null) {
//                responseEvent.getDialog().delete();
//            }
        }
    }

    @Override
    public void processTimeout(TimeoutEvent event) {
        logger.info("processTimeout {}", event);
    }

    @Override
    public void processIOException(IOExceptionEvent event) {
        logger.info("processIOException {}", event);
    }

    @Override
    public void processTransactionTerminated(TransactionTerminatedEvent event) {
        logger.info("processTransactionTerminated {}", event);
    }

    @Override
    public void processDialogTerminated(DialogTerminatedEvent event) {
        logger.info("processDialogTerminated {}", event);
    }
}
